package com.bocai.grainshop.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bocai.common.utils.R;
import com.bocai.grainshop.ware.feign.MemberFeignService;
import com.bocai.grainshop.ware.vo.FareVo;
import com.bocai.grainshop.ware.vo.MemberAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocai.common.utils.PageUtils;
import com.bocai.common.utils.Query;

import com.bocai.grainshop.ware.dao.WareInfoDao;
import com.bocai.grainshop.ware.entity.WareInfoEntity;
import com.bocai.grainshop.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(StringUtils.hasText(key)){
            wrapper.eq("id",key).or()
                    .like("name",key).or()
                    .like("address",key).or()
                    .like("areacode",key);
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        R info = memberFeignService.info(addrId);
        Object code = info.get("code");
        String s = JSON.toJSONString(code);
        Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
        });
        if(codeNum == 0){
            Object address = info.get("memberReceiveAddress");
            String add = JSON.toJSONString(address);
            MemberAddressVo addressVo = JSON.parseObject(add, new TypeReference<MemberAddressVo>() {
            });
            //简单模拟运费计算
            if(addressVo != null){
                String phone = addressVo.getPhone();
                String substring = phone.substring(phone.length() - 1, phone.length());
                fareVo.setFare(new BigDecimal(substring));
                fareVo.setAddress(addressVo);
                return fareVo;
            }
        }
        return null;
    }

}